import React, { Component } from 'react';
import { AutoComplete, Form, Modal, Select, Input, Button, Card } from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';

const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;
let modalType = null;
const formItemLayout = {
  labelCol: {
    xs: { span: 5 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};

class EditModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      modalType: null,
      name: '',
      id: '',
      fieldType: 'string',
      methods: 'add',
      childrenObj: {
        name: '',
        id: '',
        fieldType: 'string',
      },
      childrenArr: [],
      display: 'none',
      index: -1,
    };
    this.handleSelectChange = this.handleSelectChange.bind(this);
  }

  showModal = (type, val, method, index) => {
    this.setState({ childrenArr: [], display: 'none' }, () => {
      if (val) {
        this.setState({
          visible: true,
          modalType: type,
          name: val.name,
          id: val.id,
          fieldId: val.fieldId,
          fieldType: val.fieldType,
          value: val.value,
        });

        if (val.children && val.children.length > 0) {
          this.setState({
            childrenArr: val.children,
            display: 'block',
          });
        }
      } else {
        this.setState({
          visible: true,
          modalType: type,
          name: '',
          id: '',
          fieldType: 'string',
        });
      }
      if (method) {
        this.setState({
          methods: method,
        });
      } else {
        this.setState({
          methods: 'add',
        });
      }
      if (index != null || index != undefined) {
        this.setState({
          index,
        });
      } else {
        this.setState({
          index: -1,
        });
      }
      modalType = type;
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
    this.props.form.resetFields();
  };

  saveField = e => {
    e.preventDefault();
    const { addRequestFieldFun } = this.props;
    const type = this.state.modalType;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const fieldObj = values;
        fieldObj['type'] = modalType;
        if (values.fieldType === 'array') {
          /* 处理类型为数组时的表单数据 开始*/
          const childrenFields = [];
          const namesArr = [];
          const fieldTypesArr = [];
          const idsArr = [];
          for (let key in values) {
            if (key.indexOf('names_') > -1) {
              namesArr.push({ key: key, values: values[key] });
            }
            if (key.indexOf('fieldTypes_') > -1) {
              fieldTypesArr.push({ key: key, values: values[key] });
            }
            if (key.indexOf('ids_') > -1) {
              idsArr.push({ key: key, values: values[key] });
            }
          }

          for (let i in namesArr) {
            let childrens = {
              name: namesArr[i].values,
              fieldType: fieldTypesArr[i].values,
              id: idsArr[i].values,
              children: [],
            };
            childrenFields.push(childrens);
          }

          /* 处理类型为数组时的表单数据 结束*/
          // const childrenObj ={
          //   name:values.names,
          //   id:values.ids,
          //   fieldType:values.fieldTypes,
          //   children:[]
          // };
          // const childrenArr = [];
          // childrenArr.push(childrenFields);
          fieldObj['children'] = childrenFields;
          for (let index in childrenFields) {
            delete values['names_' + index];
            delete values['ids_' + index];
            delete values['fieldTypes_' + index];
          }
        } else {
          fieldObj['children'] = [];
        }
        addRequestFieldFun(
          values,
          modalType,
          this.state.methods,
          this.state.index,
          this.state.fieldId
        );

        this.setState(
          {
            value: '',
          },
          () => {
            this.handleCancel();
            this.props.form.resetFields();
          }
        );
      }
    });
  };

  checkField(rule, value, callback) {
    if (/^[0-9a-zA-Z._]{0,}$/g.test(value)) {
      callback();
    } else {
      callback('字段名只能输入英文数字小数点');
    }
  }

  addChildren() {
    const that = this;
    const arr = that.state.childrenArr;

    arr.push({
      name: '',
      id: '',
      fieldType: 'string',
      btn: true,
    });
    that.setState(
      {
        childrenArr: arr,
      },
      () => {}
    );
  }

  handleSelectChange(value) {
    const that = this;
    if (value == 'array') {
      that.setState({
        display: 'block',
      });
      that.addChildren();
    } else {
      that.setState({ childrenArr: [], display: 'none', })
    }
    that.setState({
      fieldType: value,
    });
    // that.addChildren();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Modal
          title={<FormattedMessage id="app.customApi.addOrEditField" />}
          visible={this.state.visible}
          onOk={this.saveField}
          onCancel={this.handleCancel}
          okText={<FormattedMessage id="app.customApi.apiSave" />}
          cancelText={<FormattedMessage id="app.customApi.apiCancel" />}
        >
          <Form {...formItemLayout} onSubmit={this.saveField}>
            <Form.Item
              label={<FormattedMessage id="app.customApi.Field-service-name" />}
              hasFeedback
            >
              {getFieldDecorator('name', {
                rules: [
                  {
                    required: true,
                    message: '字段业务名不可为空',
                  },
                  {
                    validator: '',
                  },
                ],
                initialValue: this.state.name,
              })(<Input placeholder="请输入字段业务名" />)}
            </Form.Item>
            <Form.Item label={<FormattedMessage id="app.customApi.Field-name" />} hasFeedback>
              {getFieldDecorator('id', {
                rules: [
                  {
                    required: true,
                    message: '请输入字段名',
                  },
                  {
                    validator: this.checkField,
                  },
                ],
                initialValue: this.state.id,
              })(<Input placeholder="请输入字段名" />)}
            </Form.Item>
            <Form.Item label="默认值" hasFeedback>
              {getFieldDecorator('value', {
                rules: [
                  {
                    required: false,
                    message: '请输入默认值',
                  },
                ],
                initialValue: this.state.value,
              })(<Input placeholder="请输入默认值" />)}
            </Form.Item>
            <Form.Item label={<FormattedMessage id="app.customApi.Field-type" />} hasFeedback>
              {getFieldDecorator('fieldType', {
                rules: [
                  {
                    required: true,
                    message: '请选择字段类型',
                  },
                  {
                    validator: '',
                  },
                ],
                initialValue: this.state.fieldType,
              })(
                <Select onChange={this.handleSelectChange}>
                  <Option value="string">字符串(string)</Option>
                  {/* {modalType === 'responseField' ? <Option value="array">数组(array)</Option> : ''} */}
                  <Option value="boolean">布尔值(boolean)</Option>
                  <Option value="short">短整型(short)</Option>
                  <Option value="int">整型(int)</Option>
                  <Option value="long">长整型(long)</Option>
                  <Option value="double">双精度型(double)</Option>
                  <Option value="float">浮点型(float)</Option>
                </Select>
              )}
            </Form.Item>
            {/* {this.state.fieldType === 'array'
              ? this.state.childrenArr.map((obj, index) => {
                  return (
                    <div key={`${index}`}>
                      <Form.Item
                        label={<FormattedMessage id="app.customApi.Field-service-name" />}
                        hasFeedback
                      >
                        {getFieldDecorator('names_' + `${index}`, {
                          rules: [
                            {
                              required: true,
                              message: '字段业务名不可为空',
                            },
                            {
                              validator: '',
                            },
                          ],
                          initialValue: obj.name,
                        })(<Input placeholder="请输入字段业务名" />)}
                      </Form.Item>
                      <Form.Item
                        label={<FormattedMessage id="app.customApi.Field-name" />}
                        hasFeedback
                      >
                        {getFieldDecorator('ids_' + `${index}`, {
                          rules: [
                            {
                              required: true,
                              message: '请输入字段名',
                            },
                            {
                              validator: this.checkField,
                            },
                          ],
                          initialValue: obj.id,
                        })(<Input placeholder="请输入字段名" />)}
                      </Form.Item>

                      <Form.Item
                        label={<FormattedMessage id="app.customApi.Field-type" />}
                        hasFeedback
                      >
                        {getFieldDecorator('fieldTypes_' + `${index}`, {
                          rules: [
                            {
                              required: true,
                              message: '请选择字段类型',
                            },
                            {
                              validator: '',
                            },
                          ],
                          initialValue: obj.fieldType,
                        })(
                          <Select>
                            <Option value="string">字符串(string)</Option>
                            <Option value="boolean">布尔值(boolean)</Option>
                            <Option value="short">短整型(short)</Option>
                            <Option value="int">整型(int)</Option>
                            <Option value="long">长整型(long)</Option>
                            <Option value="double">双精度型(double)</Option>
                            <Option value="float">浮点型(float)</Option>
                          </Select>
                        )}
                      </Form.Item>
                    </div>
                  );
                })
              : ''} */}
          </Form>
          {/* <Button
            htmlType="button"
            onClick={() => {
              this.addChildren();
            }}
            style={{ display: this.state.display }}
          >
            <FormattedMessage id="app.customApi.Continue-to-increase" />
          </Button> */}
        </Modal>
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(EditModal));
